from rest_framework import serializers
from rest_framework.relations import PrimaryKeyRelatedField

from quesanw.models import QuestionModel, TagModel, AnswerModel, QuestionTagModel, SubAnswerModel, QuestionFocusModel, \
    UsefulChangeModel, AnswerUsefulModel, UserFocusTagModel
from users.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta():
        model = User
        fields = ['id', 'username']


class QuestionTagSerializer(serializers.ModelSerializer):
    # question = QuestionSerializer()
    # tag = TagSerializer(write_only=True)
    # question = QuestionSerializer(read_only=True)
    class Meta:
        model = QuestionTagModel
        fields = '__all__'
        read_only= ('id',)

class SubCommentSerializer(serializers.ModelSerializer):
    author = UserSerializer()
    class Meta:
        model = SubAnswerModel
        fields = "__all__"


class AnswerSerializer(serializers.ModelSerializer):
    author = UserSerializer()
    subs = SubCommentSerializer(many=True)

    class Meta():
        model = AnswerModel
        fields = "__all__"
        # depth = 1

class AnswerSerializer111(serializers.ModelSerializer):
    class Meta():
        model = AnswerModel
        fields = "__all__"
        # depth = 1

    def validate_author(self,value):
        if not value:
            raise serializers.ValidationError("请先登陆～")
        try:
            user = User.objects.get(pk=value.id)
            if not user:
                raise serializers.ValidationError("用户不存在")
        except:
                raise serializers.ValidationError("数据库查询错误")
        return value
    def validate_question(self,value):
        try:
            _question = QuestionModel.objects.get(pk=value.id)
            if not _question:
                raise serializers.ValidationError("收藏的问题不存在")
        except:
            raise serializers.ValidationError("数据库查询错误")
        return value

    def create(self, validated_data):
        obj = validated_data.get("question")
        obj.comment_num =(obj.comment_num) + 1
        obj.save()
        return AnswerModel.objects.create(**validated_data)

    def update(self,instance,validated_data):
        """更新，instance为要更新的对象实例"""
        instance.author_id = validated_data.get("author",instance.author_id)
        instance.question_id = validated_data.get("question",instance.question_id)
        instance.detail = validated_data.get("detail",instance.detail)
        instance.save()
        return instance



class TagSerializer(serializers.ModelSerializer):
    class Meta():
        model = TagModel
        fields = ('name', "id", "quote_total", "info")
        depth = 1


class QuestionSerializer(serializers.ModelSerializer):
    # answer = AnswerSerializer(many=True,write_only=True)
    # id = AnswerSerializer(many=True,read_only=True)
    tag = TagSerializer(many=True)
    author = UserSerializer()
    answers = AnswerSerializer(many=True)

    # tag = serializers.PrimaryKeyRelatedField(queryset=TagModel.objects.all(), many=True, allow_null=True)

    class Meta():
        model = QuestionModel
        # fields = ['id','title','author','count','detail','comment_num','click','tag',"answermodel_set"]
        fields = "__all__"
        depth = 1
class QuestionSerializer1(serializers.ModelSerializer):

    class Meta():
        model = QuestionModel
        fields = "__all__"
        # fields = ("detail",)
    # def update(self, instance, validated_data):
    #     instance.detail = validated_data.get("detail",instance.detail)
    #     instance.save()
    #     return instance
class AnswerListSerializer(serializers.ModelSerializer):
    author = UserSerializer()
    class Meta:
        model = AnswerModel
        fields = ("create_time", "author")


class QuestionSubmitSerializer(serializers.ModelSerializer):
    tag = serializers.CharField(label='问题标签',write_only=True)
    class Meta:
        model=QuestionModel
        fields = ("title", "author",'detail',"tag","id")
        read_only= ('id',)

    def create(self, validated_data):
        tag = validated_data['tag']
        del validated_data['tag']
        question = super().create(validated_data)
        tags = tag.split(';')
        # question_id = question.id

        tags = TagModel.objects.filter(name__in=tags)
        # tag_list = TagSerializer(tags,many=True).data
        question_tag = []
        # for data in tag_list:
        #     question_tag.append({"question":question_id,"tag":data["id"]})
        for tag in tags:
            question_tag.append({'question':question,"tag":tag})
        # questiontag = QuestionTagSerializer(data=question_tag, many=True)
        # questiontag.is_valid(raise_exception=True)
        # questiontag = questiontag.data
        for data in question_tag:
            QuestionTagModel.objects.create(**data)

        return question
class UserFocusTagSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserFocusTagModel
        fields = ('user','tag','is_focus')

    def create(self,validated_data):
        tag_id = validated_data['tag'].id
        instance = super().create(validated_data)

        tag = TagModel.objects.get(id=tag_id)
        tag.quote_total += 1
        tag.save()

        return instance

    def update(self, instance, validated_data):
        super().update(instance, validated_data)
        tag_id = validated_data['tag'].id
        tag = TagModel.objects.get(id=tag_id)
        is_focus = validated_data['is_focus']
        if is_focus:
            tag.quote_total += 1
            tag.save()
        else:
            tag.quote_total -= 1
            tag.save()
        return instance
class TagQuestionSerializer(serializers.ModelSerializer):
    # question = QuestionSerializer(many=True)
    question = serializers.PrimaryKeyRelatedField(queryset=QuestionModel.objects.all(), many=True, allow_null=True)
    # tag = TagSerializer(many=True)
    tag = serializers.PrimaryKeyRelatedField(queryset=TagModel.objects.all(), many=True, allow_null=True)

    class Meta():
        model = QuestionTagModel
        fields = "__all__"


class QuestionFocusSerializer(serializers.ModelSerializer):
    class Meta():
        model = QuestionFocusModel
        fields="__all__"


    def validate_user(self,value):
        if not value:
            raise serializers.ValidationError("请先登陆～")
        try:
            user = User.objects.get(pk=value.id)
            if not user:
                raise serializers.ValidationError("用户不存在")
        except:
                raise serializers.ValidationError("数据库查询错误")
        return value
    def validate_question(self,value):
        try:
            _question = QuestionModel.objects.get(pk=value.id)
            if not _question:
                raise serializers.ValidationError("收藏的问题不存在")

        except:
            raise serializers.ValidationError("数据库查询错误")
        return value

    def create(self, validated_data):
        return QuestionFocusModel.objects.create(**validated_data)

    def update(self,instance,validated_data):
        """更新，instance为要更新的对象实例"""
        instance.user_id = validated_data.get("user").id
        instance.question_id = validated_data.get("question").id
        focus = instance.is_click
        instance.is_click=not focus

        instance.save()
        return instance

class UsefulChangeSerializer(serializers.ModelSerializer):
    # user=UserSerializer(id)

    class Meta():
        model = UsefulChangeModel
        fields="__all__"

    def validate_user(self,value):
        if not value:
            raise serializers.ValidationError("请先登陆～")
        try:
            user = User.objects.get(pk=value.id)
            if not user:
                raise serializers.ValidationError("用户不存在")
        except:
                raise serializers.ValidationError("数据库查询错误")
        return value
    def validate_question(self,value):
        try:
            _question = QuestionModel.objects.get(pk=value.id)
            if not _question:
                raise serializers.ValidationError("问题不存在")

        except:
            raise serializers.ValidationError("数据库查询错误")
        return value

    def create(self, validated_data):
        return UsefulChangeModel.objects.create(**validated_data)

    def update(self,instance,validated_data):
        """更新，instance为要更新的对象实例"""
        instance.user_id = validated_data.get("user")
        instance.question_id = validated_data.get("question")

        instance.is_useful=validated_data.get("is_useful")

        instance.save()
        return instance


class AnswerUsefulSerializer(serializers.ModelSerializer):
    # user=UserSerializer(id)

    class Meta():
        model = AnswerUsefulModel
        fields="__all__"

    def validate_user(self,value):
        if not value:
            raise serializers.ValidationError("请先登陆")
        try:
            user = User.objects.get(pk=value.id)
            if not user:
                raise serializers.ValidationError("用户不存在")
        except:
                raise serializers.ValidationError("数据库查询错误")
        return value
    def validate_question(self,value):
        try:
            _answer =AnswerModel.objects.get(pk=value.id)
            if not _answer:
                raise serializers.ValidationError("回答不存在")

        except:
            raise serializers.ValidationError("数据库查询错误")
        return value

    def create(self, validated_data):
        return AnswerUsefulModel.objects.create(**validated_data)

    def update(self,instance,validated_data):
        """更新，instance为要更新的对象实例"""
        instance.user_id = validated_data.get("user")
        instance.answer_id = validated_data.get("answer")

        instance.is_useful=validated_data.get("is_useful")

        instance.save()
        return instance





